package com.fg.core;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.core.injector.methods.*;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
import com.baomidou.mybatisplus.extension.injector.methods.InsertBatchSomeColumn;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;

@Configuration
public class MybatisPlusConfig {

    @Bean("CustomDefaultSqlInjector")
    public DefaultSqlInjector sqlInjector() {
        return new DefaultSqlInjector() {
            @Override
            public List<AbstractMethod> getMethodList(org.apache.ibatis.session.Configuration configuration, Class<?> mapperClass, TableInfo tableInfo) {
                GlobalConfig.DbConfig dbConfig = GlobalConfigUtils.getDbConfig(configuration);
                Stream.Builder<AbstractMethod> builder = Stream.<AbstractMethod>builder()
                        .add(new Insert(dbConfig.isInsertIgnoreAutoIncrementColumn()))
                        .add(new Delete())
                        .add(new Update())
                        .add(new SelectCount())
                        .add(new SelectMaps())
                        .add(new SelectObjs())
                        .add(new SelectList());
                if (tableInfo.havePK()) {
                    builder.add(new DeleteById())
                            .add(new DeleteBatchByIds())
                            .add(new UpdateById())
                            .add(new SelectById())
                            .add(new SelectBatchByIds());
                } else {
                    logger.warn(String.format("%s ,Not found @TableId annotation, Cannot use Mybatis-Plus 'xxById' Method.",
                            tableInfo.getEntityType()));
                }
                // 自定义插入批量插入
                builder.add(new InsertBatchSomeColumn(i -> i.getFieldFill() != FieldFill.UPDATE));
                return builder.build().collect(toList());
            }
        };
    }
}

